package it.intecs.pisa.smarcos.activities;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.base.BeepManager;
import it.intecs.pisa.smarcos.base.GestureEvents;
import it.intecs.pisa.smarcos.base.GestureIntents;
import it.intecs.pisa.smarcos.base.SpeechManager;
import it.intecs.pisa.smarcos.base.Lists;
import it.intecs.pisa.smarcos.util.MathUtils;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class SMSRead extends BaseActivity {

	public static final String INTENT_SHOW="it.intecs.pisa.smarcos.activities.SMSRead.SHOW";
	private static final String TAG = SMSRead.class.getSimpleName();
	public static final String EXTRA_MESSAGE_ID = "messageId";

	private SpeechManager speechManager;
	private BeepManager beepManager;
	
	View view; 
	Lists list;
	private Vibrator vibrator;
	private ViewGroup baseCenterView;
	private String position;
	LayoutInflater inflater;
	private int messageCount = 0;
	private int menuLength = 0;
	protected Cursor smsCursor=null;
	private String repeat; 

	float startX,startY;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.d(TAG, "OnCreate");

		speechManager = SpeechManager.getInstance(getApplicationContext());
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		beepManager = BeepManager.getInstance(getApplicationContext());
		
		// Metodo di BaseViewManager
		Init(getBaseContext());
		inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		view = inflater.inflate(R.layout.sms_read, null);
		setContentView(getBaseView());
		baseCenterView = (ViewGroup) findViewById(R.id.center_base_view);
		baseCenterView.addView(view);

		position = getString(R.string.MV_SMS_Read_Voice);

		String url;
		url= "content://sms/inbox"; 
	
		Uri uri = Uri.parse(url); 
		smsCursor = managedQuery(uri, 
				null,//columns, // Which columns to return
				null, // WHERE clause; which rows to return(all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)

		menuLength = smsCursor.getCount();
		speechManager.say(menuLength + getString(R.string.TTS_SMS_RECEIVED), true, false);
		if(menuLength == 0)
			onClick_A();
		
		list = new Lists(menuLength, beepManager);
	}


	@Override
	public void onResume() {
		super.onResume();

		Log.d(TAG, "onResume");
		
		passBy = false;
		speechManager.say(getString(R.string.TTS_SMS_LIST_READY), false, false);
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "OnPause");	
	}

	// CLOSE
	@Override
	public void onClick_A(){
		Log.d(TAG, "onClick_A");

		Intent returnIntent;
		returnIntent=new Intent("it.intecs.pisa.smarcos.services.ResultReceiver.SHOW");
		returnIntent.putExtra("Result", "NORESULT");
		returnIntent.addCategory(Intent.CATEGORY_DEFAULT);					
		sendBroadcast(returnIntent);
		sentResult = true;
		vibrator.vibrate(300);
		finish();
	}

	// POSITION
	@Override
	public void onClick_B(){
		Log.d(TAG, "onClick_B");
		if(position != null)
			speechManager.say(position, false, false);	
	}

	// REPEAT
	@Override
	public void onClick_C(){
		Log.d(TAG, "onClick_C");
		speechManager.say(repeat, false, false);	
	}

	// DONE -> as CLOSE 
	@Override
	public void onClick_D(){
		Log.d(TAG, "onClick_D");
		onClick_A();
	}


	@Override
	public void onClick_Center(int event, float X, float Y){
		Log.d(TAG, "onClick_Center");

		float lenghtTreshold=10;

		switch(event)
		{
		case GestureEvents.ONFLING_START:

			startX = X;
			startY = Y;
			break;

		case GestureEvents.ONFLING_STOP:

			float endX,endY;

			endX = X;
			endY = Y;

			float gestureLenght=0;

			gestureLenght=MathUtils.distanceBetweenPoints(endX,startX,endY,startY);

			if(gestureLenght>lenghtTreshold){

				String gesture = MathUtils.calculateSlice(endX,startX,endY,startY);
				if (gesture.length() != 0)
					SMSGestureHandling(gesture);
			}
			break;

		case GestureEvents.ONDOUBLETAP:
			SMSGestureHandling(GestureIntents.INTENT_GESTURE_SELECT);
			break;
			
		case GestureEvents.ONSCROLL:
			if (passBy == true)
				speechManager.say(position, false, false);
			break;
		}
	}



	private void SMSGestureHandling(String intAction) 
	{
		TextView textBody=(TextView) findViewById(R.id.SMSMessageBody);
		TextView textFrom=(TextView) findViewById(R.id.SMSMessageFrom);

		if (intAction.equals(GestureIntents.INTENT_GESTURE_SELECT)) {

			if ((messageCount = list.Movement(intAction)) == -1)
				return;
			smsCursor.moveToPosition(messageCount);
			String smsText=smsCursor.getString(smsCursor.getColumnIndex("body"));
			textBody.setText(getString(R.string.TTS_SMS_BODY)+": " +smsText );
			textBody.setTextSize(22);
			repeat += " " + getString(R.string.TTS_SMS_BODY)+smsText;
			speechManager.say(getString(R.string.TTS_SMS_BODY)+smsText, false, false);
		}
		else {
			if (intAction.equals(GestureIntents.INTENT_GESTURE_RIGHT)||
			   (intAction.equals(GestureIntents.INTENT_GESTURE_LEFT))){

				if ((messageCount = list.Movement(intAction)) == -1)
					return;
			} 

			speechManager.say("SMS " + (messageCount+1) + " di " + menuLength, true, false);
			smsCursor.moveToPosition(messageCount);
			String number=smsCursor.getString(smsCursor.getColumnIndex("address"));
			String from = getContactNameFromNumber(number);
			textBody.setText("");
			textFrom.setText(getString(R.string.TTS_SMS_FROM)+": " + from);
			textFrom.setTextSize(22);		
			repeat = getString(R.string.TTS_SMS_FROM)+from;
			speechManager.say(repeat, false, false);			
		}
	}
	
	private String getContactNameFromNumber(String number) {
		// define the columns I want the query to return
		String[] projection = new String[] {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID};
 
		// encode the phone number and build the filter URI
		Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
 
		// query time
		Cursor c = getContentResolver().query(contactUri, projection, null,	null, null);
 
		// if the query returns 1 or more results
		// return the first result
		if (c.moveToFirst()) {
			String name = c.getString(c.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
			return name;
		}
 
		c.close();
		// return the original number if no match was found
		return number;
	}
}


